package com.rainkaze.IntelliDrawNote.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.rainkaze.IntelliDrawNote.bean.TodoNote;
import com.rainkaze.IntelliDrawNote.databinding.ItemListTodoBinding;
import com.rainkaze.IntelliDrawNote.fragment.TodoListFragment;
import com.rainkaze.IntelliDrawNote.ui.TodoEditActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class TodoListAdapter extends RecyclerView.Adapter<TodoListAdapter.VH>{
    List<TodoNote> list = new ArrayList<>();

    private TodoListFragment fragment;

    public TodoListAdapter(TodoListFragment fragment) {
        this.fragment = fragment;
    }

    @NonNull
    @Override
    public TodoListAdapter.VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        ItemListTodoBinding itemListBinding = ItemListTodoBinding.inflate(layoutInflater);
        return new TodoListAdapter.VH(itemListBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull TodoListAdapter.VH holder, int position) {
        TodoNote todoNote = list.get(position);
        holder.binding.timeTv.setText(todoNote.getTime());
        holder.binding.contentTv.setText(todoNote.getContent());
        holder.binding.deadlineTv.setText(todoNote.getDdlTime());

        holder.binding.statusCheckBox.setOnCheckedChangeListener(null);

        // 设置状态
        boolean isDone = "已完成".equals(todoNote.getStatus());
        holder.binding.statusCheckBox.setChecked(isDone);
        updateTextStyle(holder, isDone);

        // 【重新绑定监听器】
        holder.binding.statusCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            todoNote.setStatus(isChecked ? "已完成" : "未完成");
            fragment.myDbHelper.updateTodo(todoNote);

            //通过异步刷新，解决了循环调用卡柱的问题
            new Thread(() -> {
                fragment.myDbHelper.updateTodo(todoNote);
                new Handler(Looper.getMainLooper()).post(() -> {
                    fragment.findAll();
                });
            }).start();
        });

        // 长按删除事件
        holder.binding.getRoot().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showDeleteDialog(todoNote, v.getContext());
                return false;
            }
        });

        // 点击编辑事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentActivity activity = fragment.getActivity();
                if (activity != null) {
                    Intent intent = new Intent(activity, TodoEditActivity.class);
                    intent.putExtra("todoNote", todoNote);
                    activity.startActivityForResult(intent, 101);
                }
            }
        });
    }

    // 删除对话框
    private void showDeleteDialog(TodoNote todoNote, Context context) {
        AlertDialog alertDialog = new AlertDialog.Builder(context)
                .setTitle("温馨提示")
                .setMessage("确定要删除该待办吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (fragment != null) {
                            fragment.myDbHelper.deleteTodo(todoNote);
                            fragment.findAll();
                            Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(context, "取消删除", Toast.LENGTH_SHORT).show();
                    }
                })
                .create();
        alertDialog.show();
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void update(List<TodoNote> todoNoteList) {
        this.list.clear();
        this.list.addAll(todoNoteList);
        notifyDataSetChanged();
    }

    public class VH extends RecyclerView.ViewHolder {
        ItemListTodoBinding binding;
        public VH(@NonNull ItemListTodoBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    // 设置状态
    private void updateTextStyle(VH holder, boolean isDone) {
        if (isDone) {
            holder.binding.contentTv.setPaintFlags(
                    holder.binding.contentTv.getPaintFlags() | android.graphics.Paint.STRIKE_THRU_TEXT_FLAG);
            holder.binding.contentTv.setTextColor(android.graphics.Color.GRAY);
            holder.binding.deadlineTv.setTextColor(Color.GRAY);
        } else {
            holder.binding.contentTv.setPaintFlags(
                    holder.binding.contentTv.getPaintFlags() & (~android.graphics.Paint.STRIKE_THRU_TEXT_FLAG));
            holder.binding.contentTv.setTextColor(android.graphics.Color.BLACK);
            holder.binding.deadlineTv.setTextColor(Color.RED);
        }
    }

}
